/**
* 参数处理
* @param {*} params  参数
*/
export function tansParams(params: any): string {
  let result = ''
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    var part = encodeURIComponent(propName) + "=";
    if (value !== null && value !== "" && typeof (value) !== "undefined") {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
            let params = propName + '[' + key + ']';
            var subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result
}

// 验证是否为blob格式
export async function blobValidate(data: any): Promise<boolean> {
  try {
    const text = await data.text();
    JSON.parse(text);
    return false;
  } catch (error) {
    return true;
  }
}

// 添加日期范围
export function addDateRange(params: any, dateRange: any, propName: string): any {
  let search = params;
  search.params = typeof (search.params) === 'object' && search.params !== null && !Array.isArray(search.params) ? search.params : {};
  dateRange = Array.isArray(dateRange) ? dateRange : [];
  if (typeof (propName) === 'undefined') {
    search.params['beginTime'] = dateRange[0];
    search.params['endTime'] = dateRange[1];
  } else {
    search.params['begin' + propName] = dateRange[0];
    search.params['end' + propName] = dateRange[1];
  }
  return search;
}


/**
 * 通用js方法封装处理
 * Copyright (c) 2019 zhiyu
 */

// 日期格式化
export function parseTime(time: any, pattern: string = '{y}-{m}-{d} {h}:{i}:{s}'): any {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

// 添加动态代码
export function dynamicLoadScript(methodName: string, code: string, callback?: Function): Promise<void> {
  return new Promise((resolve, reject) => {
    const script = document.createElement('script');
    let fn = callback || function () { };
    script.type = 'text/javascript';
    script.innerHTML = code + '\n' + `window.${methodName} = ${methodName}`;
    script.onload = function () {
      fn(window[methodName]);
    }
    document.getElementsByTagName('head')[0].appendChild(script);
  });
}

// 判断指定元素下的所有图片是否加载完毕
export async function onAllImgLoaded(root: any) {
  const imgNodes = root instanceof HTMLImageElement ? [root] : root.querySelectorAll('img');
  //为了使用Array的map方法         
  let imgArr = Array.prototype.slice.call(imgNodes);
  return await Promise.all(
    imgArr.map(img => {
      new Promise(resolve => {
        img.addEventListener('load', () => resolve(img))
      })
    })
  )
}

// 获取当前时间以及是星期几
export function getNowDateObject(dataPattern: string = '{y}年{m}月{d}日', timePattern: string = '{h}:{i}:{s}') {
  // 日期、时间
  let da = new Date();
  return {
    week: `星期${['日', '一', '二', '三', '四', '五', '六'][da.getDay()]}`,
    date: parseTime(da, dataPattern),
    time: parseTime(da, timePattern),
  }
}

// 按当前时间获取一个随机的值
export function getRandom() {
  return (+Math.random().toString().substr(3, 11) + Date.now()).toString(36)
}

// 根据src判断图片是否加载完成
export function checkImageCompleteBySrc(src: any): Promise {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.src = src
    img.onload = function () {
      if (img.complete) {
        resolve(true)
      }
    }
  })

}

/**
 * 交换数组中的元素，不会改变原始数组
 * @param arr 要交换的数组
 * @param index1 下标1
 * @param index2 下标2
 */
export function swapElements(arr: any[], index1: number, index2: number): any[] {
  const a1 = arr[index1]
  const a2 = arr[index2]
  const newArr = [...arr]
  newArr[index1] = a2
  newArr[index2] = a1
  return newArr
}